package com.hoolai.qps.mina.string;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;

import org.apache.log4j.Logger;
import org.apache.mina.core.RuntimeIoException;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

import com.hoolai.qps.mina.string.ProxyServer.Msg;

public class LogicServer {

	private static final Logger logger = Logger.getLogger(LogicServer.class);

	public final static String separator = "!@#";

	public final static String registerMsg = "!@#register!@#1001000";

	public static void main(String[] args) throws IOException {
		NioSocketConnector connector = new NioSocketConnector();
		connector.getFilterChain().addLast("codec",
				new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8"))));
		connector.getFilterChain().addLast("logger", new LoggingFilter());
		
		connector.getSessionConfig().setReadBufferSize(2048);
		
		connector.setHandler(new IoHandlerAdapter() {
			@Override
			public void messageReceived(IoSession session, Object message) throws Exception {
				if(message.toString().equals(registerMsg)){
					logger.info("logic server register success!");
				}else{
					Msg clientMsg=new Msg(message);
					session.write(new Msg(clientMsg.getUid(),clientMsg.getCmdId(),"succ"));
				}
			}

			@Override
			public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
				logger.error("exception caught:" + cause.getMessage());
			}
		});
		try {
			ConnectFuture future = connector.connect(new InetSocketAddress("127.0.0.1", 1111));
			IoSession session = future.awaitUninterruptibly().getSession();
			session.write(registerMsg);
		} catch (RuntimeIoException e) {
			System.err.println("Failed to connect.");
			e.printStackTrace();
		}
		logger.info("logic server start!");
	}

}
